package com.sunye.utils;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.awt.image.BufferedImage;

/**
 * @Author: sunye
 * @Date: 2022/5/26
 * @Description: 视频的处理类
 * @version： 1.0
 */
@Component
@Slf4j
public class VideoProcessing {
    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    public  StorePath fileUpload(String videoFileName) {
        StorePath storePath = null;
        //最后获取到的视频的图片的路径
        String videPicture="";
        //Frame对象
        Frame frame = null;
        //标识
        int flag = 0;
        try {
             /*
            获取视频文件
            */
            // FFmpegFrameGrabber fFmpegFrameGrabber = new FFmpegFrameGrabber(videoPath + "/" + videoFileName);
            FFmpegFrameGrabber fFmpegFrameGrabber = new FFmpegFrameGrabber( videoFileName);
            fFmpegFrameGrabber.start();

            //获取视频总帧数
            int ftp = fFmpegFrameGrabber.getLengthInFrames();
            log.info("时长 " + ftp / fFmpegFrameGrabber.getFrameRate() / 60);


            while (flag <= ftp) {
                frame = fFmpegFrameGrabber.grabImage();

                /*
                对视频的第四帧进行处理
                 */
                if (frame != null && flag==4) {

//                    //文件转换
                    BufferedImage bufferedImage =FileCaseUtil.FrameToBufferedImage(frame);

                    MultipartFile mf = FileCaseUtil. fileCase(bufferedImage);
                    log.info("开始文件上传:");
                    //文件上传
                    //上传视频并返回视频地址
                    storePath = fastFileStorageClient.uploadFile(mf.getInputStream(), mf.getSize(), FilenameUtils.getExtension(mf.getOriginalFilename()), null);
                    //将视频地址和项目id存到项目资料表中
//                    String videoUrl = storePath.getPath();
//                    videPicture=videoUrl;
                    log.info("文件上传成功{}",storePath.getPath());
                    break;

                }
                flag++;
            }
            fFmpegFrameGrabber.stop();
            fFmpegFrameGrabber.close();
        } catch (Exception E) {
            E.printStackTrace();
        }
        return storePath;

    }

}


